package com.yht.weblog.common.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.List;
import java.util.Objects;

/**
 * @author: yht
 * @date: 2023/12/30 12:20
 * @description: 分页响应参数工具类
 **/
@Data
@Accessors(chain = true)
public class PageResponse<T> extends Response<List<T>> {

    private long total;

    private long size;

    private long current;

    private long pages;

    /**
     * 成功响应
     *
     * @param page MybatisPlus 分页对象
     * @param data
     * @param <T>
     * @return
     */
    public static <T> PageResponse<T> success(IPage page, List<T> data) {
        PageResponse<T> response = new PageResponse<>();

        response.setSuccess(true);
        response.setCurrent(Objects.isNull(page) ? 1L : page.getCurrent());
        response.setSize(Objects.isNull(page) ? 10L : page.getSize());
        response.setPages(Objects.isNull(page) ? 0L : page.getPages());
        response.setTotal(Objects.isNull(page) ? 0L : page.getTotal());
        response.setData(data);

        return response;
    }

    /**
     *
     * @param total
     * @param current
     * @param size
     * @param data
     * @return
     * @param <T>
     */
    public static <T> PageResponse<T> success(long total, long current, long size, List<T> data) {
        PageResponse<T> response = new PageResponse<>();
        response.setSuccess(true);
        response.setCurrent(current);
        response.setSize(size);
        response.setTotal(total);
        //计算总页数
        int pages = (int) Math.ceil((double) total / size);
        response.setPages(pages);
        response.setData(data);

        return response;
    }

}
